<template>
  <a-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    class="avatar-uploader"
    :maxCount="maxCount"
    :action="http + '/admin/picture/uploadPicture?directoryName=test'"
    :before-upload="beforeUpload"
    @change="handleChange"
    @preview="handlePreview"
    :remove="remove"
    :accept="accept"
  >
    <div v-if="fileList.length < maxCount" class="ant-upload-text">
      <plus-outlined />
    </div>
  </a-upload>
  <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script>
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { computed, reactive, toRefs, ref, createVNode, watch } from 'vue'
import { uploadPicture } from '@/api/service/index.js'
import { message, Modal } from 'ant-design-vue'
import { useModal } from '@/hooks'
import { url } from '@/utils/options'
export default {
  props: {
    modelValue: {
      type: [String, Array],
      default: ''
    },
    maxCount: {
      type: Number,
      default: 1
    },
    fileName: {
      type: String,
      default: 'test'
    },
    default: {
      default: '.jpg,.png,.jpeg'
    },
    size: {
      default: 5
    }
  },
  components: {
    PlusOutlined,
    ExclamationCircleOutlined
  },
  setup(props, { emit }) {
    const http = url

    const fileList = ref([])
    const data = reactive({
      uploadLoading: false
    })

    // 监听modelValue变化，更新fileList
    watch(
      () => props.modelValue,
      newVal => {
        if (Array.isArray(newVal)) {
          fileList.value = newVal.map(url => {
            console.log('触发', url)
            return {
              uid: '-1',
              name: 'image.png',
              status: 'done',
              url: url
            }
          })
        } else {
          fileList.value = []
        }
      },
      { immediate: true }
    )

    const beforeUpload = file => {
      let arr = props.default.split(',')
      console.log(arr)

      let type = '.' + file.type.split('/')[1]
      console.log(type)

      const isJpgOrPng = arr.includes(type)
      console.log(isJpgOrPng)
      if (!isJpgOrPng) {
        message.error('文件格式不正确!')
      }
      const isLt2M = file.size / 1024 / 1024 < props.size

      if (!isLt2M) {
        message.error(`文件大小不超过${props.size}MB!`)
      }
      return isJpgOrPng && isLt2M
    }

    const handleChange = async info => {
      // if (info.file.status === 'uploading') {
      //   data.uploadLoading = true
      //   return
      // }

      if (info.file.status === 'done') {
        console.log('测试', fileList.value)

        const files = fileList.value.map(f => {
          console.log('===', f.url)
          if (f.url) {
            return f.url
          } else {
            return f.response.object
          }
        })
        console.log('files', files)
        emit('update:modelValue', files)
      }

      // if (info.file.status === 'error') {
      //   data.uploadLoading = false
      //   message.error('上传错误')
      // }
    }

    const previewVisible = ref(false)
    const previewImage = ref('')
    const previewTitle = ref('')

    const handleCancel = () => {
      previewVisible.value = false
      previewTitle.value = ''
    }

    const handlePreview = async file => {
      previewImage.value = file.url || file.preview
      previewVisible.value = true
      previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    }

    const remove = file => {
      return new Promise(resolve => {
        const files = fileList.value.filter(f => f.url !== file.url).map(f => f.url)
        emit('update:modelValue', files)
        // closeModal()
        resolve(true)
      })
    }

    return {
      fileList,
      beforeUpload,
      handleChange,
      previewVisible,
      previewImage,
      handleCancel,
      handlePreview,
      previewTitle,
      ...toRefs(data),
      remove,
      http
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
</style>
